//
//  BaseViewController.m
//
//
//  Created by miller on 14/12/15.
//  Copyright (c) 2014年 yayu wang. All rights reserved.
//

#import "BaseViewController.h"
#import "MBProgressHUD.h"
#import "UINavigationItem+CLQ.h"
#import "PXAlertView+Customization.h"
#define ScreenWidth     [UIScreen mainScreen].bounds.size.width
#define ScreenHeight    [UIScreen mainScreen].bounds.size.height
@interface BaseViewController ()
{
    MBProgressHUD* progressView; //请稍候提示框
        UIView* tipView;
}
@end

@implementation BaseViewController

- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    
    ILog(@"--------->>>>>>>>> %@ <<<<<<<<<---------",NSStringFromClass([self class]));
    
    [self addNaviBarColor];
    [self addBackNaviLeftItem];
    [self addHomePageNaviRightItem];
//    [self addHomePageNaviRightItemByImg:@"common_btn_home"];
//    [self checkSystemAdjustView];

    [self setUpForDismissKeyboard];
    
}
- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    
    ILog(@"--------->>>>>>>>> %@ <<<<<<<<<---------",NSStringFromClass([self class]));
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    self.view.backgroundColor = [Util stringTOColor:@"#f9f9f9"];
    
    float y = -50.0;
    
    if(ScreenWidth == 375)
    {
        y = 0.0;
    }
    else if(ScreenWidth == 414)
    {
        y = 50.0;
    }
    
//    tipView = [[UIView alloc] init];
//    tipView.frame = CGRectMake(0.0, y, self.view.frame.size.width, 400.0);
//    tipView.backgroundColor = [UIColor clearColor];
//    tipView.hidden = YES;
//    [self.view addSubview:tipView];

    
    //设置背景颜色
    self.view.backgroundColor = RGBCOLOR(243, 244, 246);
    
    
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor whiteColor]}];
//    self.navigationController.interactivePopGestureRecognizer.delegate = self;

}
//-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
//{
//    if(self.navigationController.viewControllers.count == 1)
//    {
//        return NO;
//    }else
//    {
//        return YES;
//    }
//
//
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)addNaviBarColor
{
    
    [self.navigationController.navigationBar setBarTintColor:RGBCOLOR(52, 124, 237)];
    [self.navigationController.navigationBar setTitleTextAttributes:
                                                                              @{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    //重写，因页面需要导航栏和下面view使用同一张图片效果
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"common_nav_bg"] forBarMetrics:UIBarMetricsDefault];
//    //去掉下面的线
//    if ([self.navigationController.navigationBar respondsToSelector:@selector(shadowImage)])
//    {
//        [self.navigationController.navigationBar setShadowImage:[UIImage imageNamed:@"FaceRecognition_line"]];
//    }
//    
//        //[self.navigationController.navigationBar setBarTintColor:[ValueUtils stringTOColor:@"#1cb7ff"]];
//        //[self.navigationController.navigationBar setTintColor:RGBCOLOR(91, 91, 93)];
//        [self.navigationController.navigationBar setTitleTextAttributes:
//         @{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:RGBCOLOR(255,255, 255)}];

}
- (void)addBackNaviLeftItem
{


    [self.navigationItem addBackItemTarget:self action:@selector(clickBack:)];
    

}

- (void)clickBack:(id)sender
{
    //默认是返回上一级
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)addHomePageNaviRightItem
{
    //[self.navigationItem addRightItemTarget:self action:@selector(gotoHomePageBtn:) andText:@"首页"];

}

- (void)addHomePageNaviRightItemByImg:(NSString* ) imgName
{
    [self.navigationItem addRightItemTarget:self action:@selector(gotoHomePageBtn:) andImageName:imgName andSize:CGSizeMake(0, 0)];
}
- (void)gotoHomePageBtn:(id)sender
{

    [self.navigationController popToRootViewControllerAnimated:YES];
    //[[NSNotificationCenter defaultCenter] postNotificationName:CMD_GotoHomePage object:self userInfo:nil];
    
}
- (void)addTitleViewWithTitle:(NSString *)title{
    //创建一个label
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100*(ScreenWidth/320), 40)];
    label.text = title;
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont fontWithName:@"American Typewriter" size:19];
    label.textAlignment = NSTextAlignmentCenter;
    
    //作为导航条的标题视图
    //属于当前视图控制器的
    self.navigationItem.titleView = label;
}
- (void)addTitleViewWithView:(UIView *)view{
    
    //作为导航条的标题视图
    //属于当前视图控制器的
    self.navigationItem.titleView = view;
}
- (void)addBarButtonItemWithTitle:(NSString *)title imageName:(NSString *)imageName frame:(CGRect)frame target:(id)target action:(SEL)action isLeft:(BOOL)isLeft isCircle:(BOOL)isCircle{
    
    return;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = frame;
    if (isCircle) {
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 10;
    }
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [button setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
//    [button setBackgroundColor:[UIColor cyanColor]];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
    if (isLeft) {
        self.navigationItem.leftBarButtonItem = item;
    }else{
        self.navigationItem.rightBarButtonItem = item;
    }
}

-(void)checkSystemAdjustView{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        [self.navigationController.navigationBar setTranslucent:NO];
    }
}

-(UIButton *)creatCustomButtonFrame:(CGRect)frame title:(NSString *)title target:(id)target action:(SEL)action tag:(NSInteger)tag{
    UIButton * allSelectButton = [UIButton buttonWithType:UIButtonTypeSystem];
    allSelectButton.frame = frame;
    [allSelectButton setTitle:title forState:UIControlStateNormal];
    allSelectButton.titleLabel.textColor = [UIColor blackColor];
    [allSelectButton addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    allSelectButton.tag = tag;
    return  allSelectButton;
}

#pragma mark - 请稍候提示框
- (void)showHudProgress_Indeterminate:(NSString* )text
{
    if (!progressView)
    {
        progressView = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [progressView setAnimationType:MBProgressHUDAnimationZoomIn];
        progressView.delegate = self;
        
    }
    
    progressView.color = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.50];
    [progressView setMode:MBProgressHUDModeIndeterminate];
    [progressView setLabelText:text];
    if ([progressView removeFromSuperViewOnHide])
    {
        [progressView show:YES];
    }
}

- (void)hideHudProgress
{
    [progressView setAnimationType:MBProgressHUDAnimationZoomOut];
    [progressView hide:YES];
}

#pragma -mark MBProgressHUDDelegate methods
- (void)hudWasHidden:(MBProgressHUD *)hud
{
    progressView.delegate = nil;
    progressView = nil;

}

- (void)showCustomHudWithTextOnly:(NSString *)text duration:(int)time{
    
    //    UIWindow* window = [UIApplication sharedApplication].keyWindow;
    //    if (!window) {
    //        window = [[UIApplication sharedApplication].windows objectAtIndex:0];
    //    }
    
    [self.view bringSubviewToFront:tipView];
    tipView.hidden = NO;
    MBProgressHUD *mHud = [MBProgressHUD showHUDAddedTo:tipView animated:YES];
    
    // Configure for text only and offset down
    mHud.mode = MBProgressHUDModeText;
    mHud.userInteractionEnabled = NO;
    mHud.detailsLabelText = text;
    mHud.margin = 10.f;
    mHud.yOffset = 150.f;
    mHud.removeFromSuperViewOnHide = YES;
    mHud.color = [ValueUtils stringTOColor:@"#555555"];//背景颜色
    mHud.alpha = .8;
    mHud.detailsLabelColor = [ValueUtils stringTOColor:@"#ffffff"];//文字颜色
    //mHud.minSize = CGSizeMake(200, 200);//最小尺寸
    [mHud hide:YES afterDelay:time];
    [tipView bringSubviewToFront:mHud];
    [self performSelector:@selector(hideTipView) withObject:nil afterDelay:time];
    
}

- (void)showHudProgress_CustomView:(NSString* )text CustomView:(UIView* )view Method:(SEL)method onTarget:(id)target
{
    if (!progressView)
    {
        progressView = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        progressView.delegate = self;
    }
    
    if(view == nil)
    {
        progressView.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"hud_checkmark.png"]];
    }
    else
    {
        progressView.customView = view;
    }
    
    progressView.color = [UIColor colorWithRed:0.23 green:0.50 blue:0.82 alpha:0.90];
    // Set custom view mode
    progressView.mode = MBProgressHUDModeCustomView;
    progressView.labelText = text;
    
    if(method == nil)
    {
        [progressView showWhileExecuting:@selector(delay:) onTarget:self withObject:nil animated:YES];
    }
    else
    {
        [progressView showWhileExecuting:method onTarget:target withObject:nil animated:YES];
    }
    
}

//延时3s关闭提示框,并返回上一级
- (void)delay:(id)sender
{
    sleep(1.0);
    [progressView hide:YES];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 弹框显示
/**
 *  显示弹框
 *
 *  @param title       标题
 *  @param message     文字内容
 *  @param cancelTitle 去学校按钮名称
 *  @param otherTitle  另外一个按钮名称
 *  @param alertType   弹框类型  一个按钮还是两个按钮  @“one” @“two”,"theone"
 *  @param completion   block 处理点击按钮事件
 */
- (void )showAlertWithTitle:(NSString*)title message:(NSString*)message cancelTitle:(NSString*)cancelTitle otherTitle:(NSString*)otherTitle alertType:(NSString*)alertType completion:(PXAlertViewCompletionBlock)completion{
    
    if ([alertType isEqualToString:@"back"]||[alertType isEqualToString:@"exit"]||[alertType isEqualToString:@"update"]||[alertType isEqualToString:@"one"]) {
        
//        [PXAlertView showAlertWithTitle:title
//                                message:message
//                            cancelTitle:cancelTitle
//                             completion:completion];
        
        [self showHudWithTextOnly:message duration:2];
    }
    
    if ([alertType isEqualToString:@"two"]) {
        PXAlertView *alert = [PXAlertView showAlertWithTitle:title
                                                     message:message
                                                 cancelTitle:cancelTitle
                                                  otherTitle:otherTitle
                                                  completion:completion];
        UIColor *blueNormal = [ValueUtils stringTOColor:@"#1cb7ff"];
        UIColor *blueSelected = [ValueUtils stringTOColor:@"#53d0ff"];
        [alert setBackgroundColor:[UIColor whiteColor]];
        [alert setMessageColor:[ValueUtils stringTOColor:@"#333333"]];
        [alert setTitleColor:[ValueUtils stringTOColor:@"#333333"]];
        [alert setCancelButtonNonSelectedBackgroundColor:blueNormal];
        [alert setCancelButtonBackgroundColor:blueSelected];
        
        UIColor *redNormal = [ValueUtils stringTOColor:@"#1cb7ff"];
        UIColor *redSelected = [ValueUtils stringTOColor:@"#53d0ff"];
        [alert setOtherButtonNonSelectedBackgroundColor:redNormal];
        [alert setOtherButtonBackgroundColor:redSelected];
        
        [alert setAllButtonsTextColor:[UIColor whiteColor]];
    }
    if ([alertType isEqualToString:@"theone"]) {
        PXAlertView *alert = [PXAlertView showAlertWithTitle:title
                                message:message
                            cancelTitle:cancelTitle
                             completion:completion];
        UIColor *blueNormal = [ValueUtils stringTOColor:@"#1cb7ff"];
        UIColor *blueSelected = [ValueUtils stringTOColor:@"#53d0ff"];
        [alert setBackgroundColor:[UIColor whiteColor]];
        [alert setMessageColor:[ValueUtils stringTOColor:@"#333333"]];
        [alert setTitleColor:[ValueUtils stringTOColor:@"#333333"]];
        [alert setCancelButtonNonSelectedBackgroundColor:blueNormal];
        [alert setCancelButtonBackgroundColor:blueSelected];

        UIColor *redNormal = [ValueUtils stringTOColor:@"#1cb7ff"];
        UIColor *redSelected = [ValueUtils stringTOColor:@"#53d0ff"];
        [alert setOtherButtonNonSelectedBackgroundColor:redNormal];
        [alert setOtherButtonBackgroundColor:redSelected];
        
        [alert setAllButtonsTextColor:[UIColor whiteColor]];
    }
    

}
//点击任何地方收起键盘
- (void)setUpForDismissKeyboard {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(tapAnywhereToDismissKeyboard:)];
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view addGestureRecognizer:singleTapGR];
                }];
    [nc addObserverForName:UIKeyboardWillHideNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view removeGestureRecognizer:singleTapGR];
                }];
}

- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
    //此method会将self.view里所有的subview的first responder都resign掉
    [self.view endEditing:YES];
}
#pragma mark - // show MBHUD Method
- (void)showHudWithTextOnly:(NSString *)text duration:(int)time{
    
    UIWindow* window = [UIApplication sharedApplication].keyWindow;
    if (!window) {
        window = [[UIApplication sharedApplication].windows objectAtIndex:0];
    }

    MBProgressHUD *mHud = [MBProgressHUD showHUDAddedTo:window animated:YES];
    
    // Configure for text only and offset down
    mHud.mode = MBProgressHUDModeText;
    mHud.userInteractionEnabled = NO;
    mHud.detailsLabelText = text;
    mHud.margin = 10.f;
    mHud.yOffset = 150.f;
    mHud.removeFromSuperViewOnHide = YES;
    mHud.color = [ValueUtils stringTOColor:@"#555555"];//背景颜色
    mHud.alpha = .8;
    mHud.detailsLabelColor = [ValueUtils stringTOColor:@"#ffffff"];//文字颜色
    //mHud.minSize = CGSizeMake(200, 200);//最小尺寸
    [window bringSubviewToFront:mHud];
    [mHud hide:YES afterDelay:time];
}
- (void)hideTipView
{
    tipView.hidden = YES;
}
@end
